/*
 Error: JSON
  	ERR:[// errors list
  			{ // Error
  			code:"%s" // error code
  			clazz:"%s" // Exception class
  			msg:"%s" // Exception message
  			stack:"%s" // Exception stack
  			}
  		]
  example: {
  	ERR:"[{code:Error1},{code:Error2}]"
  }
 Error: String
  example: "#ERR:[{code:"Error1"},{code:"Error2"}]
 */

function GetLocaleString(value){ //TODO: Реализовать локальзацию
	return value;
}

var Error={
		isError:function (obj)
		{
			if (typeof (obj) == 'object')
			{
				return obj.ERR != undefined;
			}else
			if (typeof (obj) == 'string')
			{
				return obj.search(/#ERR:/) == 0;
			}
			return false;
		},
		getErrors:function(obj)
		{
			if (Error.isError(obj))
			{
				if (typeof (obj) == 'object')
				{
					return obj.ERR;
				}else
				if (typeof (obj) == 'string')
				{
					return eval(obj.substr(5));
				}else{
					return [];
				}
			} else {
				return [];
			}
		},
		getErrorMessages:function(obj)
		{
			var errors=Error.getErrors(obj);
			if (errors != undefined)
			{
				var errorsMsg = [];
				for(var i in errors)
				{
					var error = errors[i];
					var tmp;
					if (error.code == undefined)
					{
						tmp = GetLocaleString("Errors.unknownerrorcode");
					}else
					{
						tmp = GetLocaleString("Errors."+error.code);
					}
					if (error.clazz != undefined ){
						tmp += "\nclass:'"+error.clazz+"'";
					}
					if (error.msg != undefined ){
						tmp += "\nmsg:'"+error.msg+"'";
					}
					if (error.stack != undefined ){
						tmp += "\nstack:'"+error.stack+"'";
					}
					errorsMsg.push(tmp);
				}
				return errorsMsg;
			}else
			{
				return [];
			}
		},
		testError:function()
		{
			console.log('Start test error');
			function onErrorTest(data)
			{
				if (Error.isError(data))
				{
					console.log('Test:OK');
					//console.log('Error:'+Error.getErrorMessages(data));
				}else
				{
					console.error('Test:ERROR');
				}
			}
			for (var i =0 ; i < 5 ; i++){
				MSGBroker_SendPlain(Handlers.testManager,{action:"test_error",error_mode:"str",error_suit:i},onErrorTest);
				MSGBroker_Send(Handlers.testManager,{action:"test_error",error_mode:"json",error_suit:i},onErrorTest);
			}
		}
};

var isTransportError = false;

function transportError(request, textStatus, errorThrown)
{
	if (isTransportError == true){
		return;
	}
	isTransportError = true;
	if (confirm("Connection error.\nReload page?")){
		window.location.reload();
		return;
	}
	isTransportError = false;
};


jQuery.ajaxSetup({
	error:transportError
});

